package com.stedu.security;

import com.stedu.exception.CaptchaException;
import com.stedu.service.impl.UserDetailsServiceImpl;
import com.stedu.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
* 验证码过滤器
* 1.正确：放行
* 2.不正确：登录失败处理
* */
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private  LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        /*判断，放行
        * 请求和地址是否是/login
        * 是否是post请求
        *不满足就要放行
        * */

        //获取请求方式
        String method = request.getMethod();
        // 获取请求地址
        String requestURI = request.getRequestURI();
        if (method.equalsIgnoreCase("POST") && requestURI.equals("/login")){
            try {
                //判断验证码是否正确
                //先获取用户发送过来的key和验证码
                //根据发送过来的key去redis获取正确的验证码
                //判断 正确-放行  不正确-抛出自定义的异常
                String key = request.getParameter("key");
                String captchaInput = request.getParameter("captchaInput");
                if (key==null||captchaInput==null){
                    throw  new CaptchaException("验证码不为空");
                }
                //根据发送过来的key去redis获取正确的验证码
                String captcha = (String)redisUtil.get(key);
                if (!captcha.equalsIgnoreCase(captchaInput)){
                    throw  new CaptchaException("验证码错误");
                }
            }catch (CaptchaException e){
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
            //放行


        }
        filterChain.doFilter(request, response);
    }
}
